<template>
  <div style="text-align: center">
    <el-transfer
      style="text-align: left; display: inline-block"
      v-model="value"
      :titles="['未拥有', '已拥有']"
      :button-texts="['移除', '添加']"
      :data="data"
    ></el-transfer>
    <el-row style="margin: 20px 0 0 0">
      <el-button type="primary" @click="addRoles()">确认分配</el-button>
      <el-button type="info" plain @click="closed()">取消分配</el-button>
    </el-row>
  </div>
</template>
<script>
import userApi from "@/api/user";
import roleApi from "@/api/role";
import { Message } from "element-ui";
export default {
  data() {
    return {
      data: [],
      value: []
    };
  },
  props: {
    id: ""
  },
  created() {
    this.getAllRole();
    this.getRolesByUId(this.id);
  },
  watch: {
    id: {
      handler(newVal) {
        this.id = newVal;
        this.getRolesByUId(newVal);
      },
      immediate: true
    }
  },
  methods: {
    getAllRole() {
      roleApi.getAllRole().then(res => {
        var q = res.data.data;
        q.forEach(({ id, roleName, remark }) => {
          var k = {
            id,
            roleName,
            remark
          };
          this.data.push({
            key: k.id,
            label: remark,
            disabled: false
          });
        });
      });
    },
    getRolesByUId(id) {
      userApi.getRolesByUId(id).then(res => {
        var q = res.data.data;
        q.forEach(({ id, roleName, remark }) => {
          var k = {
            id,
            roleName,
            remark
          };
          this.value.push(k.id);
        });
      });
    },
    closed() {
      this.value=[]
      this.$emit("closeDialog");
      this.getRolesByUId(this.id);
    },
    addRoles() {
      if(this.value.length>1){
        Message.error("只能分配一个角色！");
        return
      }else if(this.value==""){
        Message.error("后台不能设置游客！");
        return
      }
      userApi.addRoles(this.value, this.id).then(res => {
        Message.success(res.message);
        this.closed();
      });
    }
  }
};
</script>
<style scoped>
</style>